#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, getopt, switch
import telnetlib
import time

def usage():
	print "This script only works if running-config = startup-config"
	print "Otherwise you need tu run the command manually on the switch"
	print "usage: reload [-h] [-a address]"
	print "\t-a or --address\t specify the IP address of the switch"
	print "\t-h\t\t display this help"
	print

def run_reload(ip):
	print "Connecting to " + ip + "..."
	tn = switch.connect(ip)
	if not tn:
		print "Error while connecting to " + str(ip)
		sys.exit(3)
		#continue
	name = switch.enable(tn)
	if not name:
		print "Error while connecting to " + ip
		sys.exit(4)
		#continue
	print "Connected on " + name

	print "Rebooting switch with IP " + ip + " called " + name
	switch.run_command(tn, "reload")

	
	
	# On confirme le rebooot
	tn.write("\n")
	
	# TODO : gérer le cas ou running-config != startup-config -> seconde confirmation nécessaire ...
	# Ou alors renvoyer simplement une erreure ... 



def main(argv):
	try:
		opts, args = getopt.getopt(argv[1:], "a:h", ["help", "address="])
	except getopt.GetoptError:
		usage()
		sys.exit(2)
	ip_switch = ""
	for opt, arg in opts:
		if opt in ("-h", "--help"):
			usage()
			sys.exit()
		elif opt in ("-a", "--address"):
			ip_switch = arg
	if ip_switch == "":
		usage()
		sys.exit(2)
	run_reload(ip_switch)

if __name__ == "__main__":
	main(sys.argv)
